package router

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
	"synthesis-server/middle"
	"synthesis-server/model"
	"synthesis-server/server"
)

/*
	将http连接升级为websocket连接到的代码
*/
var upGrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
	Subprotocols: []string{},
}

func RunWebSocket(c *gin.Context) {

	user := middle.TokenClaims.User.ID
	ty := middle.TokenClaims.User.Type
	//println("websocket能否从token中解析出用户信息", user, ty)
	if user == "" {
		fmt.Println("尝试建立websocket连接的客户的user字段未填充,用户建立连接失败!")
		return
	}
	upGrader.Subprotocols = []string{c.GetHeader("sec-websocket-protocol")}

	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}

	client := &server.Client{
		Name:     user,
		Conn:     ws,
		Send:     make(chan []byte),
		Working:  true,
		IsServer: false,
		IsLining: false,
	}

	//判断当前用户是否已经登录系统
	for k, _ := range server.MyServer.Clients {
		if k == client.Name {
			d := model.Datas{DataType: "reLogin"}
			m := model.Msg{Data: d}
			data, err := json.Marshal(m)
			if err != nil {
				fmt.Println("服务器向客服发送socket连接已经建立的消息json序列化不成功!")
			}
			client.Conn.WriteMessage(websocket.TextMessage, data)
			client.Conn.Close()
			return
		}
	}

	//将登入的客户端信息填写进服务器的map
	server.MyServer.Clients[client.Name] = client

	/*
		先判断接入的客户端的身份是客服还是客户
	*/
	if ty == "server" {
		client.IsServer = true
		//server.MyServer.IdleServer.Add(client)

		d := model.Datas{DataType: "websocketConnect"}
		m := model.Msg{Data: d}
		data, err := json.Marshal(m)
		if err != nil {
			fmt.Println("服务器向客服发送socket连接已经建立的消息json序列化不成功!")
		}
		client.Conn.WriteMessage(websocket.TextMessage, data)
		server.MyServer.Mutex.Lock()
		server.MyServer.OnlineServer++
		server.MyServer.Mutex.Unlock()
		server.MyServer.ServerIn <- client
		////客服登录的时候给客服发送排队人数和在线客服数量
		//status := model.Status{OnlineServer: strconv.Itoa(server.MyServer.OnlineServer), WaitingClients: strconv.Itoa(len(server.MyServer.WaitingClient.Data))}
		//msg, er := json.Marshal(status)
		//if er != nil {
		//	fmt.Println("客服登录时发送status信息失败")
		//}
		//dd := model.Datas{DataType: "status", DataContent: string(msg)}
		//send := model.Msg{Data: dd}
		//sendData, e := json.Marshal(send)
		//if e != nil {
		//	fmt.Println("客服登录时发送status信息失败")
		//}
		//client.Conn.WriteMessage(websocket.TextMessage, sendData)

	} else {
		/*
			接入的客户端是客户:
					检查空闲客服队列,
				1.若有空闲客服且排队队列为0则直接建立和客服的通话,
				2.若无空闲客服则先进入排队队列,
				3.若当前无客服在线则返回当前无客服在线并关闭socket连接
		*/

		if len(server.MyServer.IdleServer.Data) != 0 {
			if len(server.MyServer.WaitingClient.Data) == 0 {
				//1.有空闲客服且无人排队     直接建立连接    并向该用户发送连接成功建立的信息
				s := server.MyServer.IdleServer.Pop()
				server.MyServer.Calling[client] = s
				//向客户发送连接成功建立的消息
				d := model.Datas{DataType: "p2pConnect", DataContent: s.Name}
				m := model.Msg{Data: d}
				data, err := json.Marshal(m)
				if err != nil {
					fmt.Println("1服务器向客户发送连接建立成功的消息json序列化不成功!")
				}
				client.Conn.WriteMessage(websocket.TextMessage, data)

				//向客服发送p2p连接成功建立的消息
				da := model.Datas{DataType: "p2pConnect", DataContent: client.Name}
				ma := model.Msg{Data: da}
				dataa, err := json.Marshal(ma)
				if err != nil {
					fmt.Println("2服务器向客服发送连接建立成功的消息json序列化不成功!")
				}
				s.Conn.WriteMessage(websocket.TextMessage, dataa)

			}

		} else if server.MyServer.OnlineServer > 0 {
			//2.若无空闲客服则先进入排队队列
			client.IsLining = true
			waitingPeopleNum := len(server.MyServer.WaitingClient.Data)
			server.MyServer.WaitingClient.Add(client)
			d := model.Datas{DataType: "FrontPeople", DataContent: strconv.Itoa(waitingPeopleNum)}
			m := model.Msg{Data: d}
			data, err := json.Marshal(m)
			if err != nil {
				fmt.Println("服务器向客户发送要排队的消息json序列化不成功!")
			}
			client.Conn.WriteMessage(websocket.TextMessage, data)
			server.MyServer.BroadcastStatus()
		} else if server.MyServer.OnlineServer == 0 {
			//3.若当前无客服在线则返回当前无客服在线并关闭socket连接
			d := model.Datas{DataType: "no online service,connect shut down"}
			m := model.Msg{Data: d}
			data, err := json.Marshal(m)
			if err != nil {
				fmt.Println("服务器向客户发送当前没有客服在线!此会话关闭的消息json序列化不成功!")
			}
			client.Conn.WriteMessage(websocket.TextMessage, data)
			delete(server.MyServer.Clients, client.Name)
			client.Conn.Close()
		}
		//server.MyServer.BroadcastStatus()
	}

	//client.Conn.WriteMessage(websocket.TextMessage, []byte("与服务器的websocket连接已经建立"))
	go client.Read()
	go client.Write()
}
